package org.lboot.llog.listener;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.lboot.llog.domain.ApiLogDTO;
import org.lboot.llog.event.ApiLogCreatedEvent;
import org.lboot.llog.module.ApiLogEntity;
import org.lboot.llog.module.ApiLogService;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author kindear
 * 接口日志创建事件
 */
@Slf4j
@Component
@AllArgsConstructor
public class ApiLogListener implements ApplicationListener<ApiLogCreatedEvent> {
    ApiLogService logService;
    @Override
    @Async
    public void onApplicationEvent(ApiLogCreatedEvent event) {
        ApiLogDTO dto = event.getApiLog();
        String module = dto.getModule();
        // 非包含模块,则令其重新查询
        List<String> modules = logService.getDistinctModule();
        if (!modules.contains(module)){
             logService.resetModules();
        }
        ApiLogEntity apiLog = new ApiLogEntity();
        BeanUtil.copyProperties(dto,apiLog, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        logService.saveOne(apiLog);
    }
}
